import React from 'react';
import _ from 'underscore';

import { Scope } from 'lib/scopeFactory';

import { defaultApi } from '../../apis/core-util';

import EventEditor from './EventEditor.jsx';

export default class MetaScope extends Scope {
  constructor(props, context) {
    super(props, context);

    this.$state = {
      isHiddenEvent: true,
      eventCount: '--',
      lastData: null,
      grid: {
        loading: true
      }
    }; // $state

    this.$state.cols = [
      {
        title: '事件名称',
        sortable: true,
        key: 'name',
        render: (url, rowData) => (
          <a href="javascript:;" onClick={ this.showEditor.bind(this, rowData) }>
            { url }
          </a>
        )
      }, {
        title: '事件中文名称',
        sortable: true,
        key: 'cname'
      }, {
        title: '是否隐藏',
        key: 'visible',
        formatter: value => value ? '可见' : '隐藏'
      }, {
        title: '编辑',
        key: 'editor',
        render: (cellValue, rowData) => (
          <a
            href="javascript:;"
            className="iconfont"
            onClick={ this.showEditor.bind(this, rowData) }>
            &#xe637;
          </a>
        )
      }
    ]; // cols

    this.gridApi = defaultApi({
      __url: `sd/${ BlueWare.appId }/api/events/all`,
      cache: false,
      invisible: true
    });
  } // constructor

  showEditor(item) {
    EventEditor.mount({
      target: item,
      draggable: true,
      onClose: () => this.fetch()
    });
  } // showEditor

  $toggle_events(payload) {
    this.$state.isHiddenEvent = !this.$state.isHiddenEvent;
    this.convertData();
    this.emit();
  } // toggle_events

  convertData() {
    if (!this.$state.lastData) {
      return;
    }

    let data = _.chain(this.$state.lastData)
                .filter(item => {
                  if (item.virtual) {
                    return false;
                  }
                  if (item.visible) {
                    return true;
                  }
                  if (!this.$state.isHiddenEvent && !item.visible) {
                    return true;
                  }
                  return false;
                }, this)
                .value();
    this.$state.eventCount = data.length;
    this.$state.grid = { data };
  }

  fetch() {
    this.gridApi
        .fetch()
        .fail(error => this.$state.grid = { error })
        .done(data => {
          this.$state.lastData = data;
          this.convertData();
        })
        .always(() => this.emit());
  } // fetch

  $load() {
    this.fetch();
  } // $load
}
